package com.study.javaBasic.reflection;

import java.lang.reflect.Method;

/**
 * 方法相关:
 *
 * @author WS
 */
public class MethodInfo {
    public static void main(String[] args) throws Exception {
        Class stdClass = Student.class;
        // 获取public方法getScore，参数为String:
        System.out.println(stdClass.getMethod("setScore", int.class));
        // 获取继承的public方法getName，无参数:
        System.out.println(stdClass.getMethod("getName"));
        // 获取private方法getGrade，参数为int:
        System.out.println(stdClass.getDeclaredMethod("setGrade", int.class));


        Method getInfo = getMethodByName(stdClass, "getInfo");
        Student student = (Student) stdClass.newInstance();
        Object invoke = getInfo.invoke(student, 12);
        System.out.println(invoke);
    }

    static Method getMethodByName(Class cls, String name) {
        Method[] declaredMethods = cls.getDeclaredMethods();
        for (int i = 0; i < declaredMethods.length; i++) {
            if (declaredMethods[i].getName().equalsIgnoreCase(name))
                return declaredMethods[i];
        }
        return null;
    }
}
